"""Import batch repository implementation (Synchronous)."""

from __future__ import annotations

from uuid import UUID

from sqlalchemy.orm import Session

from ..models.import_batch import ImportBatch, ImportStatus
from .base import Repository
from ..schemas.import_batch import ImportBatchCreate, ImportBatchUpdate


class ImportBatchRepository(Repository[ImportBatch, ImportBatchCreate, ImportBatchUpdate]):
    """Repository for ImportBatch operations (Synchronous)."""

    def __init__(self, session: Session) -> None:
        super().__init__(ImportBatch, session)

    def get_by_user(self, user_id: int, skip: int = 0, limit: int = 20) -> list[ImportBatch]:
        """Get import batches by user with pagination."""
        return (
            self.session.query(ImportBatch)
            .filter(ImportBatch.imported_by == user_id)
            .order_by(ImportBatch.created_at.desc())
            .offset(skip)
            .limit(limit)
            .all()
        )

    def get_all(self, skip: int = 0, limit: int = 50) -> list[ImportBatch]:
        """Get all import batches with pagination (admin only)."""
        return (
            self.session.query(ImportBatch)
            .order_by(ImportBatch.created_at.desc())
            .offset(skip)
            .limit(limit)
            .all()
        )

    def get_by_status(self, status: ImportStatus) -> list[ImportBatch]:
        """Get all batches with a specific status."""
        return (
            self.session.query(ImportBatch)
            .filter(ImportBatch.status == status)
            .order_by(ImportBatch.created_at.desc())
            .all()
        )

    def update_status(
        self,
        batch_id: UUID,
        status: ImportStatus,
        record_count: int | None = None,
        errors_count: int | None = None,
        warnings_count: int | None = None,
        duplicates_count: int | None = None,
    ) -> ImportBatch | None:
        """Update batch status, record count, and statistics."""
        batch = self.get(batch_id)
        if batch is None:
            return None

        batch.status = status
        if record_count is not None:
            batch.record_count = record_count
        if errors_count is not None:
            batch.errors_count = errors_count
        if warnings_count is not None:
            batch.warnings_count = warnings_count
        if duplicates_count is not None:
            batch.duplicates_count = duplicates_count

        self.session.commit()
        self.session.refresh(batch)
        return batch
